package com.masterclient.app.businessmodule.minemodule.index;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.ams.common.util.StringUtil;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.UIUtils;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.eoner.baselibrary.widget.PermissionDialog;
import com.eoner.managerlibrary.Tools;
import com.eoner.managerlibrary.weixin.WeiXinManager;
import com.eoner.middlelib.eventbus.EventBusManager;
import com.eoner.middlelib.eventbus.event.WXSendCancelEvent;
import com.eoner.middlelib.eventbus.event.WXSendFailedEvent;
import com.eoner.middlelib.eventbus.event.WXSendSuccessEvent;
import com.masterclient.app.R;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.CropCircleWithBorderTransformation;

public class InviteFriendDialog extends Dialog {

    @BindView(R.id.dialog_invite_avatar)
    ImageView inviteAvatar;
    @BindView(R.id.dialog_invite_name)
    TextView inviteName;
    @BindView(R.id.dialog_invite_qr)
    ImageView inviteQr;
    @BindView(R.id.dialog_invite_code)
    TextView inviteCode;
    @BindView(R.id.dialog_invite_friends)
    View inviteFriends;
    @BindView(R.id.dialog_invite_circle)
    View inviteCircle;
    @BindView(R.id.dialog_invite_download)
    View inviteDownload;
    @BindView(R.id.dialog_invite_layout)
    LinearLayout inviteLayout;

    private String url, name, avatar, invite_code;
    private Context context;
    private RxPermissions rxPermissions;

    public InviteFriendDialog(@NonNull Activity context, String url, String name, String avatar, String invite_code) {
        super(context);
        this.context = context;
        this.url = url;
        this.name = name;
        this.avatar = avatar;
        this.invite_code = invite_code;
        rxPermissions = new RxPermissions(context);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_invite_friends);
        ButterKnife.bind(this);

        inviteQr.setImageBitmap(Tools.createQRImage(url, ScreenUtils.dp2px(190), ScreenUtils.dp2px(190)
                , BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher)));

        ViewTransformUtil.glideImageView(context, avatar, inviteAvatar,
                new Transformation[]{new CropCircleWithBorderTransformation(0, context.getResources()
                        .getColor(R.color.transparent)), new CenterCrop()}, R.mipmap.user_head_default_icon);

        inviteName.setText(name);
        inviteCode.setText(invite_code);


    }

    @OnClick({R.id.dialog_invite_friends, R.id.dialog_invite_circle, R.id.dialog_invite_download,R.id.dialog_invite_cancel})
    void onClick(View view){
        switch (view.getId()){
            case R.id.dialog_invite_friends:
                if (Tools.isAppAvilible(context,"com.tencent.mm")) {
                    share(true);
                } else {
                    ToastUtil.showToast("请先安装微信客户端");
                }
                break;
            case R.id.dialog_invite_circle:

                if (Tools.isAppAvilible(context,"com.tencent.mm")) {
                    share(false);
                } else {
                    ToastUtil.showToast("请先安装微信客户端");
                }
                break;
            case R.id.dialog_invite_download:
                boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (!hasPermissions){
                    new PermissionDialog(context, "开启相册权限", "保存图片需要获取保存到相册权限，请在下一个页面点击“允许”",
                            R.mipmap.bg_permission, () -> requestPermissions()).show();
                }else {
                    savePic();
                }
                break;
            case R.id.dialog_invite_cancel:
                dismiss();
                break;
        }
    }


    private void share(boolean isSession){
        boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (!hasPermissions){
            new PermissionDialog(context, "开启相册权限", "保存图片需要获取保存到相册权限，请在下一个页面点击“允许”",
                    R.mipmap.bg_permission, () -> requestPermissions(isSession)).show();
        }else {
            savePic(isSession);
        }
    }

    private void requestPermissions(){
        rxPermissions
                .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission.granted) {
                        savePic();
                    } else if (permission.shouldShowRequestPermissionRationale) {
                    } else {
                        ToastUtil.showToast("保存文件权限申请失败,无法保存图片");
                    }
                    dismiss();
                });
    }

    private void requestPermissions(boolean isSession){
        rxPermissions
                .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission.granted) {
                        savePic(isSession);
                    } else if (permission.shouldShowRequestPermissionRationale) {
                    } else {
                        Toast.makeText(context, "保存文件权限申请失败,无法保存图片", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void savePic(){
        Bitmap bitmap = getBitmap();
        if (bitmap == null) return;
        String path = UIUtils.getSaveImagePath(context, bitmap);
        if (!TextUtils.isEmpty(path)) {
            ToastUtil.showToast("保存成功");
        } else {
            ToastUtil.showToast("保存失败");
        }
        bitmap.recycle();
        dismiss();
    }

    private void savePic(boolean isSession){
        Bitmap bitmap = getBitmap();
        if (bitmap == null) return;
        String path = UIUtils.getSaveImagePath(context, bitmap);
        if (WeiXinManager.checkVersionValid(context) && WeiXinManager.checkAndroidNotBelowN()) {
            path = WeiXinManager.getFileUri(context, new File(path));
        }
        if (!TextUtils.isEmpty(path)) {
            wxSharePic("he" + System.currentTimeMillis(),isSession,bitmap, path);
        } else {
            Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
        }
        bitmap.recycle();
    }

    private void wxSharePic(String transaction,boolean isSession,Bitmap bitmap, String path) {
        WXImageObject imageObject;
        if (!StringUtil.isBlank(path)) {
            imageObject = new WXImageObject();
            imageObject.imagePath = path;
        } else {
            imageObject = new WXImageObject(bitmap);
        }
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imageObject;
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
        bitmap.recycle();
        msg.thumbData = Utils.bmpToByteArray(scaledBitmap,false);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = transaction + Long.toString(System.currentTimeMillis());
        req.message = msg;
        req.scene = isSession ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
        IWXAPI api = WXAPIFactory.createWXAPI(context, WeiXinManager.APP_ID);
        api.sendReq(req);
    }


    public Bitmap getBitmap() {
        int h = inviteLayout.getHeight();
        Bitmap bitmap = null;
        bitmap = Bitmap.createBitmap(inviteLayout.getWidth(), h, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        Drawable background = inviteLayout.getBackground();
        if (background instanceof ColorDrawable) {
            ColorDrawable colorDrawable = (ColorDrawable) background;
            int color = colorDrawable.getColor();
            canvas.drawColor(color);
        }
        inviteLayout.draw(canvas);
        return bitmap;
    }

    /**
     * 成功
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendSuccess(WXSendSuccessEvent successEvent) {
        Toast.makeText(context, "分享成功", Toast.LENGTH_LONG).show();
        dismiss();

    }

    /**
     * 取消
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendCancel(WXSendCancelEvent cancelEvent) {
        Toast.makeText(context, "分享取消", Toast.LENGTH_LONG).show();
        dismiss();

    }

    /**
     * 失败
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendFailed(WXSendFailedEvent failedEvent) {
        Toast.makeText(context, "分享失败", Toast.LENGTH_LONG).show();
        dismiss();
    }

    @Override
    public void show() {
        EventBusManager.register(this);
        super.show();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        EventBusManager.unRegister(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Window window = getWindow();
        WindowManager.LayoutParams windowparams = window.getAttributes();
        windowparams.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setGravity(Gravity.BOTTOM);
        window.setBackgroundDrawableResource(R.color.black_99);
        window.setAttributes(windowparams);
    }
}
